package interpreter;

import java.util.Stack;

/**
 * 上下文信息，存储运行结果
 */
public class ExpContext {

    //当前运算结果
    private Integer result;
    //用栈保存表达式
    private Stack<IExpression> stack = new Stack<>();

    public ExpContext(String exp) {
        this.parse(exp);
    }

    //将表达式进行分割
    private void parse(String exp) {
        String[] arr = exp.split(" ");
        for (int i = 0; i < arr.length; i++) {
            String str = arr[i];
            if (str.equals("+")){
                IExpression left = stack.pop();
                IExpression right = new NumberExp(arr[++i]);
                AddExp addExp = new AddExp(left, right);
                //结果入栈
                stack.push(new NumberExp(addExp.interpret()+""));
            }else if(str.equals("-")){
                IExpression left = stack.pop();
                IExpression right = new NumberExp(arr[++i]);
                SubExp subExp = new SubExp(left, right);
                //结果入栈
                stack.push(new NumberExp(subExp.interpret()+""));
            }else{
                stack.push(new NumberExp(str));
            }
        }
    }

    //获取结果
    public int calcuate(){
        return stack.pop().interpret();
    }
}
